/*
 * Copyright (c) 2018. cangoonline.net All Rights Reserved.
 * 类名称：JobBaseController.java
 * 创建人：韩伟
 * 联系方式：hanwei@cangoonline.com
 */
package com.cango.job.controller;

import com.alibaba.fastjson.JSONObject;
import com.cango.job.vo.JobResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * Author: hanwei
 * CreateDate: 2019/8/19
 */
@RestController
@RequestMapping("/job")
public abstract class JobBaseController {
    Logger logger = LoggerFactory.getLogger(JobBaseController.class);
    public static final String RESPONSE_CODE_SUCCESS = "0000";
    public static final String RESPONSE_CODE_ERROR = "9999";
    public static final String ERROR_DECRYPT = "9997";
    public static final String ERROR_AUTHCODE_INVALID = "9998";


    @RequestMapping(value = "/schedule", method = RequestMethod.POST)
    public JobResult schedule(String method, String params) {
        String factParam = null;
        try {
            factParam = decrypt(params, getKey());
        } catch (Exception e) {
            logger.error("解密请求参数错误", e);
            return new JobResult(ERROR_DECRYPT, "解密请求参数错误");
        }

        try {
            JSONObject jsonObject = JSONObject.parseObject(factParam);
            if (null == jsonObject || !jsonObject.containsKey("authCode") || !getAuthCode().equals(jsonObject.getString("authCode"))) {
                return new JobResult(ERROR_AUTHCODE_INVALID, "系统验证码错误");
            }

            String paramStr = jsonObject.getString("data");
            JSONObject pj = null;
            if(!StringUtils.isEmpty(paramStr) && !"{}".equals(paramStr)){
                pj= JSONObject.parseObject(paramStr);
            }
            return service(method, pj);
        } catch (Exception e) {
            logger.error("调用job程序出现未知错误", e);
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            return new JobResult(RESPONSE_CODE_ERROR, "调用job程序出现未知错误:" + sw.toString());
        }
    }

    public abstract JobResult service(String method, JSONObject param);

    public String getKey() {
        return "1234567890123456";
    }

    public String getAuthCode() {
        return "1234567890123456";
    }


    /**
     * 加密--把加密后的byte数组先进行二进制转16进制在进行base64编码
     *
     * @param sSrc
     * @param sKey
     * @return
     * @throws Exception
     */
    public static String encrypt(String sSrc, String sKey) throws Exception {
        if (sKey == null) {
            throw new IllegalArgumentException("Argument sKey is null.");
        }
        if (sKey.length() != 16) {
            throw new IllegalArgumentException(
                    "Argument sKey'length is not 16.");
        }
        byte[] raw = sKey.getBytes("ASCII");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

        byte[] encrypted = cipher.doFinal(sSrc.getBytes("UTF-8"));
        String tempStr = parseByte2HexStr(encrypted);

        com.thoughtworks.xstream.core.util.Base64Encoder encoder = new com.thoughtworks.xstream.core.util.Base64Encoder();
        return encoder.encode(tempStr.getBytes("UTF-8"));
    }

    /**
     * 解密--先 进行base64解码，在进行16进制转为2进制然后再解码
     *
     * @param sSrc
     * @param sKey
     * @return
     * @throws Exception
     */
    public static String decrypt(String sSrc, String sKey) throws Exception {

        if (sKey == null) {
            throw new IllegalArgumentException("499");
        }
        if (sKey.length() != 16) {
            throw new IllegalArgumentException("498");
        }

        byte[] raw = sKey.getBytes("ASCII");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);

        com.thoughtworks.xstream.core.util.Base64Encoder encoder = new com.thoughtworks.xstream.core.util.Base64Encoder();
        byte[] encrypted1 = encoder.decode(sSrc);

        String tempStr = new String(encrypted1, "utf-8");
        encrypted1 = parseHexStr2Byte(tempStr);
        byte[] original = cipher.doFinal(encrypted1);
        String originalString = new String(original, "utf-8");
        return originalString;
    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
                    16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }
}
